import React, { Component } from 'react';
import './input.scss'
import PropTypes from 'prop-types';

export default class Input extends Component {
  constructor (props) {
    super(props)
    this.state = {
      value: props.value
    }
    this.onChange = this.onChange.bind(this)
    this.onClick = this.onClick.bind(this)
    this.onFocus = this.onFocus.bind(this)
    this.onBlur = this.onBlur.bind(this)
  }
  formItem () {
    return this.context.FormItem
  }
  componentWillUpdate (props) {
    if (props.value !== this.props.value) {
      this.setState({
        value: props.value
      })
    }
  }
  onChange (e) {
    const value = e.target.value
    this.props.onChange && this.props.onChange(value)
    // form
    this.formItem() && this.formItem().onInputChange && this.formItem().onInputChange()
  }
  onClick (e) {
    e.nativeEvent.stopImmediatePropagation();
    this.props.onClick && this.props.onClick()
  }
  onFocus () {
    this.props.onFocus && this.props.onFocus()
  }
  onBlur () {
    this.props.onBlur && this.props.onBlur()
    // form
    this.formItem() && this.formItem().onInputBlur && this.formItem().onInputBlur()
  }
  render () {
    return (
      <input type="input"
      value={this.state.value}
      onChange={this.onChange}
      className="tbcInput"
      onClick={this.onClick}
      onFocus={this.onFocus}
      onBlur={this.onBlur}></input>
    )
  }
}

Input.contextTypes = { // 定义了contextTypes，this.context才有值
  FormItem: PropTypes.any
};